package com.jzmy.employment.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.example.commons.entity.ResumesDO;
import com.example.commons.entity.UserDO;
import com.example.commons.entity.UserRoleDO;
import com.example.commons.utils.ApiEnumError;
import com.example.commons.utils.ApiResult;
import com.example.commons.utils.IdCardUtil;
import com.example.commons.utils.JWTUtil;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.jzmy.employment.entity.ApplicationRecord;
import com.jzmy.employment.entity.RecruitmentNews;
import com.jzmy.employment.entity.Resumes;
import com.jzmy.employment.entity.vo.ApplicationRecordVo;
import com.jzmy.employment.entity.vo.RecruitmentNewsVo;
import com.jzmy.employment.entity.vo.RetVO;
import com.jzmy.employment.feign.UserOpenfeign;
import com.jzmy.employment.service.ApplicationRecordService;
import com.jzmy.employment.service.Pinyin4jUtil;
import com.jzmy.employment.service.RecruitmentNewsService;
import com.jzmy.employment.service.ResumesService;
import com.jzmy.employment.service.impl.RecruitmentNewsServiceImpl;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import static com.example.commons.utils.TokenTag.TOKEN_TAG;
import static com.jzmy.employment.config.AMapUtils.addressToGPS;
import static org.apache.commons.codec.binary.StringUtils.newString;

/**
 * @author mengzhichao
 * @create 2022-08-26-9:31
 */
@Slf4j
@RestController
@RequestMapping("/recruitment")
public class ApiRecruitmentController {


    @Autowired
    private RecruitmentNewsService recruitmentNewsService;

    @Autowired
    private ResumesService resumesService;

    @Autowired
    private ApplicationRecordService applicationRecordService;

    @Autowired
    private UserOpenfeign userOpenfeign;




    public int getStringCount(String str,String searchChar) {
        int count = 0;

        int origialLength = str.length();
        str = str.replace(searchChar, "");
        int newLength = str.length();

        count = origialLength - newLength;
        System.out.println("字符" + searchChar + "出现的次数为：" + count);
        return count;
    }





    /**
     * api小程序端-招聘岗位列表接口--公开方法，不需要登录
     *
     * @Description: 招聘岗位列表接口（需分页），参数：页码，显示数，岗位名称，0热门/1最新（筛选条件）,市,工资,福利介绍
     * @Param: [current, number, name, type, city，salary，welfareInroduce]
     */
    @GetMapping("/selJobList")
    @Transactional
    public ApiResult<?> selJobList(String current, String number, String name, String type, String city, String salary,String welfareInroduce,String likeName,String orgName) {
        if(StringUtils.isBlank(type)){
            return ApiResult.lack("");//缺少参数
        }
        //判断是否为数字
        if (!IdCardUtil.isNumeric(type)) {
            return ApiResult.format("");//格式错误
        }
        Map map = new HashMap();
        map.put("statusValue",1);

        if(StringUtils.isNotBlank(likeName)){
            map.put("likeName",likeName);
        }

        //名称
        if(StringUtils.isNotBlank(name)){
            map.put("name",name);
        }
        //地址
        if(StringUtils.isNotBlank(city)){
            map.put("city",city);
        }
        //薪资
        if(StringUtils.isNotBlank(salary)){
            map.put("salary",salary);
        }

        //福利介绍
        if(StringUtils.isNotBlank(welfareInroduce)){
            map.put("welfareInroduce", welfareInroduce );
        }

        if(StringUtils.isNotBlank(orgName)){
            map.put("orgName", orgName);
        }

        Page<RecruitmentNewsVo> page = recruitmentNewsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map,type);
        List<RecruitmentNewsVo> records = page.getRecords();
        for (int i=0;i<records.size();i++){
            if (records.get(i).getSalaryRange()!=null&&!"".equals(records.get(i).getSalaryRange())){
                records.get(i).setSalaryRange(jeFormat(records.get(i).getSalaryRange()));
            }
        }
        page.setRecords(records);
        return ApiResult.success(page);
    }


    /**
     * api小程序端-省市区查询
     *
     * @Param: [id]
     */
    @GetMapping("/selectRegion")
    public ApiResult<?> selectRegion(String name){
        if (name == null||"".equals(name)){
            return ApiResult.fail("缺少参数");
        }
        List<String> data =  recruitmentNewsService.selectRegion(name);
        return ApiResult.success(data);
    }


    /**
     * 查询所有市
     */
    @GetMapping("/selectCity")
    public ApiResult<?> selectCity(String name){
        List<String> data = recruitmentNewsService.selectCity(name);
        List<Map<String,String>> css =new ArrayList<>();
        //将城市拼音首字母取出放入map
        for (int i=0;i<data.size();i++){
            Map<String,String> cs =new HashMap<>();
            cs.put("first_zimu",Pinyin4jUtil.getFirstLetter(data.get(i))); //首字母
            cs.put("city_name",data.get(i));//汉字
            css.add(cs);
        }
        //按城市拼音进行排序
        css.sort(Comparator.comparing(cs -> cs.get("first_zimu")));

        Map<String, List<Map<String, String>>> jg = css.stream()
                .collect(Collectors.groupingBy(item -> item.get("first_zimu"),LinkedHashMap::new,Collectors.toCollection(ArrayList::new)));


        List<RetVO> retVOS =new ArrayList<>();

        for (String key:jg.keySet()){
            RetVO retVO =new RetVO();
            retVO.setIdx(key);
            List<Map<String,String>> list = jg.get(key);
            retVO.setCities(list);
            retVOS.add(retVO);
        }
        System.out.println(retVOS);
        return ApiResult.success(retVOS);
    }




    /**
     * api小程序端-招聘岗位详情接口
     *
     * @Description: 获取岗位信息详情，参数：岗位id
     * @Param: [id]
     */
    @GetMapping("/selJobDetails")
    @Transactional
    public ApiResult<?> selJobDetails(String id) {
        if(StringUtils.isBlank(id)){
            return ApiResult.lack("");//缺少参数
        }
        RecruitmentNews recruitmentNews = recruitmentNewsService.getById(Long.parseLong(id));
        recruitmentNews.setBrowseNumber(recruitmentNews.getBrowseNumber() + 1);
        boolean b = recruitmentNewsService.updateById(recruitmentNews);
        if(b){
            RecruitmentNews recruitmentNew = recruitmentNewsService.selJobDetails(Long.parseLong(id));
            recruitmentNew.setSalaryRange(jeFormat(recruitmentNew.getSalaryRange()));
            String address = recruitmentNew.getAddress(); //获取到地址
            double[] doubles = addressToGPS(address);
            recruitmentNew.setLatitude(doubles[1]);
            recruitmentNew.setLongitude(doubles[0]);
            System.out.println(address+"、经度: "+doubles[0]);
            System.out.println(address+"、纬度: "+doubles[1]);
            return ApiResult.success(recruitmentNew);
        }else{
            return ApiResult.fail("信息错误，请重试");
        }
    }


    @GetMapping("/selJobDetailIsStatus")
    public ApiResult<?> selJobDetailIsStatus(String id) {
        RecruitmentNews recruitmentNews = recruitmentNewsService.getById(Long.parseLong(id));
        UserDO user = JWTUtil.getUser();
        if (null == user) {
            return ApiResult.invalid();
        }
        if (user!=null&&user.getId()!=null){
           ApplicationRecord applicationRecord = applicationRecordService.findOneByKv("user_id",user.getId(),"rnews_id",Long.parseLong(id));
            recruitmentNews.setIsStatus(applicationRecord==null?0:applicationRecord.getState());
        }
        return ApiResult.success(recruitmentNews.getIsStatus());
    }



    @GetMapping("/isToken")
    public ApiResult<?> isToken(String token) {
        boolean tokenExpired = JWTUtil.isTokenExpired(token);
        return ApiResult.success(tokenExpired);
    }



    /**
     * api小程序端-投递简历接口
     *
     * @Description: 用户投递简历；参数：验证token，招聘岗位id
     * @Param: [token, id]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-27
     */
    @PostMapping("/addResume")
    @Transactional
    public ApiResult<?> addResume(String id) {
        UserDO user = JWTUtil.getUser();
        if (null == user) {
            return ApiResult.invalid();
        }
        if(StringUtils.isBlank(id)){
            return ApiResult.lack("");//缺少参数
        }

        Resumes resumes = resumesService.findOneByKv("user_id",user.getId());
        if(resumes != null){
            RecruitmentNews recruitmentNews = recruitmentNewsService.getById(Long.parseLong(id));
            if(recruitmentNews != null){
                ApplicationRecord applicationRecord = applicationRecordService.findOneByKv("user_id",user.getId(),"rnews_id",Long.parseLong(id));
                if(applicationRecord == null){
                    ApplicationRecord applicationRecord1 = new ApplicationRecord();
                    applicationRecord1.setUserId(user.getId());//用户id
                    applicationRecord1.setOrgId(recruitmentNews.getOrgId());//机构id
                    applicationRecord1.setRnewsId(Long.parseLong(id));//招聘岗位id
                    applicationRecord1.setAppTime(new Date());//应聘时间
                    applicationRecord1.setCreaterDate(new Date());//创建时间
                    applicationRecord1.setState(2);//默认沟通中
                    applicationRecord1.setType(0);
                    boolean b = applicationRecordService.save(applicationRecord1);
                    if(b){
                        recruitmentNews.setAppNumber(recruitmentNews.getAppNumber() + 1);
                        recruitmentNewsService.updateById(recruitmentNews);

                        return ApiResult.success("投递成功，请静候佳音！");
                    }else{
                        return ApiResult.fail("投递失败，请刷新重试！");
                    }
                }else{
                    return ApiResult.fail("您已投递，请勿重复！");
                }
            }else{
                return ApiResult.fail("信息错误，请刷新重试！");
            }
        }else{
            return ApiResult.build(ApiEnumError.NORESUMES.getCode(), ApiEnumError.NORESUMES.getMsg());
        }
    }




    /**
     * api小程序端-简历投递记录列表接口
     *
     * @Description: 获取当前用户的简历投递记录列表信息；参数：验证token，页码，显示数，状态（0成功，1失败，2沟通中）（筛选条件)
     * @Param: [token, current, number, state]
     */
    @GetMapping("/selApplicationRecord")
    @Transactional
    public ApiResult<?> selApplicationRecord(String current, String number,String state) {
        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
        if (null == user) {
            return ApiResult.invalid();
        }
        if(StringUtils.isBlank(state)){
            return ApiResult.lack("");//缺少参数
        }
        //判断是否为数字
        if (!IdCardUtil.isNumeric(state)) {
            return ApiResult.format("");//格式错误
        }

        Map map = new HashMap();
        map.put("userId",user.getId());
        map.put("state",state);
        Page<ApplicationRecordVo> page = applicationRecordService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        List<ApplicationRecordVo> records = page.getRecords();
        for (int i=0;i<records.size();i++){
            if (records.get(i).getSalaryRange()!=null&&!"".equals(records.get(i).getSalaryRange())){
                records.get(i).setSalaryRange(jeFormat(records.get(i).getSalaryRange()));
            }
        }
        page.setRecords(records);
        return ApiResult.success(page);
    }




    private String jeFormat(String je){
        String[] array = splitStrArray(je);
        boolean b = sumValue(array);
        if (b){
            String sum1 = getNumberFromString(array[0]);
            sum1 = String.valueOf(Integer.valueOf(sum1) / 1000);
            String sum2 = getNumberFromString(array[1]);
            sum2 = String.valueOf(Integer.valueOf(sum2) / 1000);
            String rst = sum1 + "k" +"-"+ sum2 +"k";
            return rst;
        }else {
            return "未知";
        }
    }


    private boolean sumValue(String [] array){
        if (array.length<2){
            return false;
        }
        return true;
    }


    /**
     * 将字符串按照 - 拆分为指定字符
     * @param str
     * @return
     */
    public String[] splitStrArray(String str) {
        if (str != null) {
            return str.split("-");
        }
        return null;
    }


    /**
     * 从 String 中提取数字
     * */
    public String getNumberFromString(String string){
        String str = string;
        str = str.trim();
        StringBuffer str2 = new StringBuffer();  // 此处可以也使用StringBuffer
        if(str != null && !"".equals(str)) {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                    String s = String.valueOf(str.charAt(i));
                    // 为什么不用＋号拼接，当然是因为＋号拼接效率最慢的问题啊
                    str2.append(s);
                }
            }
        }
        return str2.toString();
    }



    /**
     * api小程序端-提交和修改我的简历接口
     *
     * @Description: 提交和修改我的简历;参数：验证token，期望职业，期望月薪，籍贯，毕业院校，工作年限，教育经历，工作经验，自我评价
     * @Param: [token, desiredOccupation, expectedSalary, nativePlace, graduatedFrom, workYears, educationExperience, workExperience, selfEvaluation]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     */
    @PostMapping("/updResume")
    @Transactional
    public ApiResult<?> updResume(Resumes resumes2) throws UnsupportedEncodingException {
        System.out.println("前端传来的数据+++++++++++++++++++++++++++++"+resumes2);
        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
//        UserDO user =new UserDO();
//        user.setId(1509349086594027522L);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (resumes2.getBySchool()!=null) {
            resumes2.setBySchool(URLDecoder.decode(resumes2.getBySchool(), "utf-8"));
            System.out.println("解码:" + resumes2.getBySchool());
        }

        if (resumes2.getXmName()!=null) {
            resumes2.setXmName(URLDecoder.decode(resumes2.getXmName(), "utf-8"));
            System.out.println("解码:" + resumes2.getXmName());
        }


        if (resumes2.getGsName()!=null) {
            resumes2.setGsName(URLDecoder.decode(resumes2.getGsName(), "utf-8"));
            System.out.println("解码:" + resumes2.getGsName());
        }

        if (resumes2.getZsName()!=null) {
            resumes2.setZsName(URLDecoder.decode(resumes2.getZsName(), "utf-8"));
            System.out.println("解码:" + resumes2.getZsName());
        }

        UserDO updateUser = userOpenfeign.getUserById(user.getId());
        QueryWrapper<RecruitmentNews> wrapper=new QueryWrapper<>();
        boolean b;
        boolean b1 =false;
        Resumes resumes = resumesService.findOneByKv("user_id",user.getId());

        if(resumes != null){
            if (StrUtil.isNotBlank(resumes2.getUserName())){ //用户名
                updateUser.setName(resumes2.getUserName());
            }
            if (StrUtil.isNotBlank(resumes2.getMobile())){ //手机号
                updateUser.setMobile(resumes2.getMobile());
            }
            if (null!=resumes2.getSex()){ //性别
                updateUser.setSex(resumes2.getSex());
            }
            System.out.println("前端传的头像路径+++++++++++++++++++++++++++++"+resumes2.getHeadPortrait());
            if (null!=resumes2.getHeadPortrait()){ //头像
                updateUser.setHeadPortrait(resumes2.getHeadPortrait());
            }
            //编辑用户信息时，记得添加角色信息，否则或导致后期角色错误
            List<Long> userRoleId = userOpenfeign.listRoleId(updateUser.getId().toString());
            updateUser.setRoleIds(userRoleId);

            System.out.println(resumes2.getGsName() == null?"新增+++++++++++++++++++++++++++":"修改+++++++++++++++++++++++++++");
            if (resumes2.getGsName()!=null && !resumes2.getGsName().equals("")){ //工作经验
                resumes.setWorkExperience(setUpdateJson(resumes.getWorkExperience(),resumes2.getGsName(),resumes2.getWorkExperience()));
            }else {
                if(StrUtil.isNotBlank(resumes2.getWorkExperience())){
                    String yy = resumes.getWorkExperience(); //获取到原有的
                    String yxg = resumes2.getWorkExperience();//获取到要修改的
                    if (StrUtil.isNotBlank(yy)&&!"".equals(yy)) {
                        Integer bngIndex = getStrIndex(yy, "}", getStringCount(yy,"}"));
                        yy = yy.substring(0,bngIndex);
                        System.out.println("前半部分json串"+yy);
                        yxg = yxg.substring(2,yxg.length());
                        System.out.println("后半部分json串"+yxg);
                        yxg = yy+ "}"+","+"{" + yxg;
                        System.out.println("结果："+yxg);
                    }else {
                        yxg = resumes2.getWorkExperience();
                    }
                    resumes.setWorkExperience(yxg);
                }
            }


            if(StrUtil.isNotBlank(resumes2.getWorkYears())){
                resumes.setWorkYears(resumes2.getWorkYears());//工作年限
            }
            if(StrUtil.isNotBlank(resumes2.getAge())){
                resumes.setAge(resumes2.getAge());//年龄
            }
            if(resumes2.getConceal()!=null){
                resumes.setConceal(resumes2.getConceal());//是否隐藏
            }
            if(StrUtil.isNotBlank(resumes2.getNativePlace())){
                resumes.setNativePlace(resumes2.getNativePlace());//贯籍
            }
            if(StrUtil.isNotBlank(resumes2.getGraduatedFrom())){
                resumes.setGraduatedFrom(resumes2.getGraduatedFrom());//毕业院校
            }
            if(StrUtil.isNotBlank(resumes2.getDesiredOccupation())){
                resumes.setDesiredOccupation(resumes2.getDesiredOccupation());//期望职业
            }
            if(StrUtil.isNotBlank(resumes2.getExpectedSalary())){
                resumes.setExpectedSalary(resumes2.getExpectedSalary());//期望月薪
            }
            if(StrUtil.isNotBlank(resumes2.getSelfEvaluation())){
                resumes.setSelfEvaluation(resumes2.getSelfEvaluation());//自我评价
            }
            System.out.println(resumes2.getBySchool() == null?"新增+++++++++++++++++++++++++++":"修改+++++++++++++++++++++++++++");
            if (resumes2.getBySchool()!=null && !resumes2.getBySchool().equals("")){
                resumes.setEducationExperience(setUpdateJson(resumes.getEducationExperience(),resumes2.getBySchool(),resumes2.getEducationExperience()));
            }else {
                if(StrUtil.isNotBlank(resumes2.getEducationExperience())){
                    String educationExperience = resumes.getEducationExperience(); //获取到原有的
                    String newEducationExperience = resumes2.getEducationExperience();//获取到要修改的
                    if (StrUtil.isNotBlank(educationExperience)&&!"".equals(educationExperience)) {
                        Integer bngIndex = getStrIndex(educationExperience, "}", getStringCount(educationExperience,"}"));
                        educationExperience = educationExperience.substring(0,bngIndex);
                        System.out.println("前半部分json串"+educationExperience);
                        newEducationExperience = newEducationExperience.substring(2,newEducationExperience.length());
                        System.out.println("后半部分json串"+newEducationExperience);
                        newEducationExperience = educationExperience+ "}"+","+"{" + newEducationExperience;
                        System.out.println("结果："+newEducationExperience);
                    }else {
                        newEducationExperience = resumes2.getEducationExperience();
                    }
                    resumes.setEducationExperience(newEducationExperience);//教育经历
                }
            }

            if(resumes2.getApplyState()!=null){
                resumes.setApplyState(resumes2.getApplyState());//求职状态0：立即到岗，1：月内到岗，2：考虑机会，3：暂不考虑）
            }
            if(StrUtil.isNotBlank(resumes2.getJobAddress())){
                resumes.setJobAddress(resumes2.getJobAddress());//工作地点
            }
            if(resumes2.getIsPush()!=null){
                resumes.setIsPush(resumes2.getIsPush());//是否自动推送到实习就业单位（0：否 ，1：是）
            }
            if(resumes2.getJobNature()!=null){
                resumes.setJobNature(resumes2.getJobNature());//工作性质（0：全职，1：兼职，2：实习）
            }
            if(StrUtil.isNotBlank(resumes2.getSkills())){
                resumes.setSkills(resumes2.getSkills());//专业技能
            }


            System.out.println(resumes2.getXmName() == null?"新增+++++++++++++++++++++++++++":"修改+++++++++++++++++++++++++++");
            if (resumes2.getXmName()!=null && !resumes2.getXmName().equals("")){ //项目经历
                resumes.setProject(setUpdateJson(resumes.getProject(),resumes2.getXmName(),resumes2.getProject()));
            }else {
                if(StrUtil.isNotBlank(resumes2.getProject())){
                    String yy = resumes.getProject(); //获取到原有的
                    String yxg = resumes2.getProject();//获取到要修改的
                    if (StrUtil.isNotBlank(yy)&&!"".equals(yy)) {
                        Integer bngIndex = getStrIndex(yy, "}", getStringCount(yy,"}"));
                        yy = yy.substring(0,bngIndex);
                        System.out.println("前半部分json串"+yy);
                        yxg = yxg.substring(2,yxg.length());
                        System.out.println("后半部分json串"+yxg);
                        yxg = yy+ "}"+","+"{" + yxg;
                        System.out.println("结果："+yxg);
                    }else {
                        yxg = resumes2.getProject();
                    }
                    resumes.setProject(yxg);//项目经历
                }
            }



            System.out.println(resumes2.getZsName() == null?"新增+++++++++++++++++++++++++++":"修改+++++++++++++++++++++++++++");
            if (resumes2.getZsName()!=null && !resumes2.getZsName().equals("")){ //荣誉证书
                resumes.setCertificate(setUpdateJson(resumes.getCertificate(),resumes2.getZsName(),resumes2.getCertificate()));
            }else {
                if(StrUtil.isNotBlank(resumes2.getCertificate())){

                    String yy = resumes.getCertificate(); //获取到原有的
                    String yxg = resumes2.getCertificate();//获取到要修改的
                    if (StrUtil.isNotBlank(yy)&&!"".equals(yy)) {
                        Integer bngIndex = getStrIndex(yy, "}", getStringCount(yy,"}"));
                        yy = yy.substring(0,bngIndex);
                        System.out.println("前半部分json串"+yy);
                        yxg = yxg.substring(2,yxg.length());
                        System.out.println("后半部分json串"+yxg);
                        yxg = yy+ "}"+","+"{" + yxg;
                        System.out.println("结果："+yxg);
                    }else {
                        yxg = resumes2.getCertificate();
                    }
                    resumes.setCertificate(yxg);
                }
            }

            if (StrUtil.isNotBlank(resumes2.getEducation())){
                resumes.setEducation(resumes2.getEducation());//学历
            }
            b = resumesService.updateById(resumes);
            System.out.println("执行修改用户操作++++++++++++++++++++++++++++++++++++++++++++++++++++++用户信息为："+updateUser);
            Boolean c = userOpenfeign.userUpdateById(updateUser);
            System.out.println("用户信息修改结果"+c);
            if(resumes.getIsPush()!=null){

                if(resumes.getIsPush()==1){
                    wrapper.like("name" , resumes.getDesiredOccupation());
                    b1=true;
                }

            }
        }else{
            if (StrUtil.isNotBlank(resumes2.getUserName())){ //用户名
                updateUser.setName(resumes2.getUserName());
            }
            if (StrUtil.isNotBlank(resumes2.getMobile())){ //手机号
                updateUser.setMobile(resumes2.getMobile());
            }
            if (null!=resumes2.getSex()){ //性别
                updateUser.setSex(resumes2.getSex());
            }
            System.out.println("前端传的头像路径+++++++++++++++++++++++++++++"+resumes2.getHeadPortrait());
            if (null!=resumes2.getHeadPortrait()){ //头像
                updateUser.setHeadPortrait(resumes2.getHeadPortrait());
            }
            //编辑用户信息时，记得添加角色信息，否则或导致后期角色错误
            List<Long> userRoleId = userOpenfeign.listRoleId(updateUser.getId().toString());
            updateUser.setRoleIds(userRoleId);
            Boolean c = userOpenfeign.userUpdateById(updateUser);
            System.out.println("用户信息修改结果"+c);
            Resumes resumes1 = new Resumes();
            resumes1.setUserId(user.getId());//用户id
            resumes1.setState(0);//默认上线
            // if(!com.qiniu.util.StringUtils.isNullOrEmpty(resumesDO2.getWorkExperience())){
            resumes1.setWorkExperience(resumes2.getWorkExperience());//工作经验
            // }
            // if(!com.qiniu.util.StringUtils.isNullOrEmpty(resumesDO2.getWorkYears())){
            resumes1.setWorkYears(resumes2.getWorkYears());//工作经验
            // }
            // if(!com.qiniu.util.StringUtils.isNullOrEmpty(resumesDO2.getNativePlace())){
            resumes1.setNativePlace(resumes2.getNativePlace());//工作经验
            // }
            // if(!com.qiniu.util.StringUtils.isNullOrEmpty(resumesDO2.getGraduatedFrom())){
            resumes1.setGraduatedFrom(resumes2.getGraduatedFrom());//工作经验
            // }
            resumes1.setDesiredOccupation(resumes2.getDesiredOccupation());//工作经验
            resumes1.setExpectedSalary(resumes2.getExpectedSalary());//月薪
            resumes1.setSelfEvaluation(resumes2.getSelfEvaluation());//工作经验
            resumes1.setEducationExperience(resumes2.getEducationExperience());//工作经验
            resumes1.setApplyState(resumes2.getApplyState());//工作经验
            resumes1.setJobAddress(resumes2.getJobAddress());//工作经验
            resumes1.setIsPush(resumes2.getIsPush());//工作经验
            resumes1.setJobNature(resumes2.getJobNature());//工作经验
            resumes1.setSkills(resumes2.getSkills());//工作经验
            resumes1.setProject(resumes2.getProject());//工作经验
            resumes1.setCertificate(resumes2.getCertificate());//工作经验
            resumes1.setEducation(resumes2.getEducation());//学历
            resumes1.setSex(resumes2.getSex());//性别
            resumes1.setAge(resumes2.getAge()); //年龄
            resumes1.setConceal(resumes2.getConceal());//是否隐藏

            System.out.println("执行保存简历操作++++++++++++++++++++++++++++++++++++++++++++++++++++++简历信息为："+resumes1);
            b = resumesService.save(resumes1);
            if(resumes1.getIsPush()!=null){

                if(resumes1.getIsPush()==1){
                    wrapper.like("name" , resumes1.getDesiredOccupation());
                    b1=true;
                }
            }
        }
        if(b){
            //  if (resumesDO.getIsPush() == 1){
            //匹配该用户期望职业的招聘信息


//            List<RecruitmentNews> recNewsList = recruitmentNewsService.list(wrapper);
//            if (recNewsList.size() != 0){
//                int i =0;
//                for (RecruitmentNews recNews : recNewsList){
//                    System.out.println("第"+i+"次循环+++++++++++++++++++++++++++++++++++++++++");
//                    i++;
//                    //自动投递简历·
//                    ApplicationRecord appRecord = applicationRecordService.findOneByKv("rnews_id" , recNews.getId(), "user_id" , user.getId());
//                    if (appRecord == null){
//                        ApplicationRecord applicationRecord = new ApplicationRecord();
//                        applicationRecord.setRnewsId(recNews.getId());
//                        applicationRecord.setOrgId(recNews.getOrgId());
//                        applicationRecord.setUserId(user.getId());
//                        applicationRecord.setState(2);
//                        applicationRecord.setAppTime(new Date());
//                        applicationRecord.setCreaterDate(new Date());
//                        applicationRecordService.save(applicationRecord);
//                    }
//                }
//            }
            return ApiResult.success();
        }else{
            if(b1){
                return ApiResult.success();
            }else {
                return ApiResult.fail("提交错误");
            }
        }
    }



    /**
     * api小程序端-查看我的简历接口
     *
     * @Description: 查看我的简历；参数：验证token
     * @Param: [token]
     */
    @GetMapping("/selResumeUser")
    @Transactional
    public ApiResult<?> selResumeUser(Long id) {
        if(id==null){
            return ApiResult.fail("非法请求！");
        }
        Resumes resumes = resumesService.findOneByKv("id",id);
        return ApiResult.success(resumes);
    }







    /**
     * api小程序端-查看我的简历接口
     *
     * @Description: 查看我的简历；参数：验证token
     * @Param: [token]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-23
     */
    @GetMapping("/selResume")
    public ApiResult<?> selResume(String bySchool,String xmName,String gsName,String zsName) throws UnsupportedEncodingException {

        if (bySchool!=null) {
            bySchool = URLDecoder.decode(bySchool, "utf-8");
            System.out.println("解码:" + bySchool);
        }


        if (xmName!=null) {
            xmName = URLDecoder.decode(xmName, "utf-8");
            System.out.println("解码:" + xmName);
        }


        if (gsName!=null) {
            gsName = URLDecoder.decode(gsName, "utf-8");
            System.out.println("解码:" + gsName);
        }

        if (zsName!=null) {
            zsName = URLDecoder.decode(zsName, "utf-8");
            System.out.println("解码:" + zsName);
        }

        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
        UserDO rstUser = userOpenfeign.getUserById(user.getId());
        if (null == user) {
            return ApiResult.invalid();
        }
        Resumes resumesDO = resumesService.findOneByKv("user_id",user.getId());

        if (resumesDO!=null) {
            if (resumesDO.getEducationExperience() == null) {
                resumesDO.setEducationExperience("[]");
            }
        }

        if (bySchool!=null&&!"".equals(bySchool)) {
            if (resumesDO.getEducationExperience() != null && !"".equals(resumesDO.getEducationExperience())) { //如果教育经历字段不为空
                String json = resumesDO.getEducationExperience();//json串
                int index = 1; //默认第一次出现的位置
                List<String> list =new ArrayList<>();
                for (int i=0;i<100;i++) {
                    Integer bngIndex = getStrIndex(json, "{", index);
                    Integer endIndex = getStrIndex(json, "}", index);
                    if (bngIndex<0){
                        break;
                    }
                    System.out.println(bngIndex + "," + endIndex);
                    String substring = json.substring(bngIndex, endIndex+1);
                    list.add(substring);
                    index++;
                }
                for (int i=0;i<list.size();i++){
                    String str = list.get(i);
                    boolean is = str.contains(bySchool);
                    if (is){
                        resumesDO.setEducationExperience(str);
                        break;
                    }
                }
            }
        }


        if (xmName!=null&&!"".equals(xmName)) {
            if (resumesDO.getProject() != null && !"".equals(resumesDO.getProject())) { //如果教育经历字段不为空
                String json = resumesDO.getProject();//json串
                int index = 1; //默认第一次出现的位置
                List<String> list =new ArrayList<>();
                for (int i=0;i<100;i++) {
                    Integer bngIndex = getStrIndex(json, "{", index);
                    Integer endIndex = getStrIndex(json, "}", index);
                    if (bngIndex<0){
                        break;
                    }
                    System.out.println(bngIndex + "," + endIndex);
                    String substring = json.substring(bngIndex, endIndex+1);
                    list.add(substring);
                    index++;
                }
                for (int i=0;i<list.size();i++){
                    String str = list.get(i);
                    boolean is = str.contains(xmName);
                    if (is){
                        resumesDO.setProject(str);
                        break;
                    }
                }
            }
        }

        //工作经历
        if (gsName!=null&&!"".equals(gsName)) {
            if (resumesDO.getWorkExperience() != null && !"".equals(resumesDO.getWorkExperience())) {
                String json = resumesDO.getWorkExperience();//json串
                int index = 1; //默认第一次出现的位置
                List<String> list =new ArrayList<>();
                for (int i=0;i<100;i++) {
                    Integer bngIndex = getStrIndex(json, "{", index);
                    Integer endIndex = getStrIndex(json, "}", index);
                    if (bngIndex<0){
                        break;
                    }
                    System.out.println(bngIndex + "," + endIndex);
                    String substring = json.substring(bngIndex, endIndex+1);
                    list.add(substring);
                    index++;
                }
                for (int i=0;i<list.size();i++){
                    String str = list.get(i);
                    boolean is = str.contains(gsName);
                    if (is){
                        resumesDO.setWorkExperience(str);
                        break;
                    }
                }
            }
        }

        //荣誉证书
        if (zsName!=null&&!"".equals(zsName)) {
            if (resumesDO.getCertificate() != null && !"".equals(resumesDO.getCertificate())) {
                String json = resumesDO.getCertificate();//json串
                int index = 1; //默认第一次出现的位置
                List<String> list =new ArrayList<>();
                for (int i=0;i<100;i++) {
                    Integer bngIndex = getStrIndex(json, "{", index);
                    Integer endIndex = getStrIndex(json, "}", index);
                    if (bngIndex<0){
                        break;
                    }
                    System.out.println(bngIndex + "," + endIndex);
                    String substring = json.substring(bngIndex, endIndex+1);
                    list.add(substring);
                    index++;
                }
                for (int i=0;i<list.size();i++){
                    String str = list.get(i);
                    boolean is = str.contains(zsName);
                    if (is){
                        resumesDO.setCertificate(str);
                        break;
                    }
                }
            }
        }


        if (resumesDO != null){
            if (rstUser.getEmail() != null){
                resumesDO.setEmail(rstUser.getEmail());
            }
            if (rstUser.getSex() != null){
                resumesDO.setSex(rstUser.getSex());
            }
            if (rstUser.getHeadPortrait() != null){
                resumesDO.setHeadPortrait(rstUser.getHeadPortrait());
            }
            if (rstUser.getName() != null){
                resumesDO.setUserName(rstUser.getName());
            }
            if (rstUser.getDateOfBirth() != null){
                resumesDO.setDateOfBirth(rstUser.getDateOfBirth());
            }
            if (rstUser.getMobile() != null){
                resumesDO.setMobile(rstUser.getMobile());
            }
        }
        return ApiResult.success(resumesDO);
    }


    /**
     * 获取指定字符指定次数出现的下标
     * @param str
     * @param param
     * @param count
     * @return
     */
    private static Integer getStrIndex(String str,String param,Integer count){
        int a = StringUtils.ordinalIndexOf(str, param, count);
        return a;
    }


    private static String setUpdateJson(String selectJson,String bySchool,String updateJson){
        updateJson = updateJson.substring(1,updateJson.length()-1);
        String rst = "";
        if (selectJson!=null&&!"".equals(selectJson)) {
                int index = 1; //默认第一次出现的位置
                List<String> list =new ArrayList<>();
                for (int i=0;i<100;i++) {
                    Integer bngIndex = getStrIndex(selectJson, "{", index);
                    Integer endIndex = getStrIndex(selectJson, "}", index);
                    if (bngIndex<0){
                        break;
                    }
                    System.out.println(bngIndex + "," + endIndex);
                    String substring = selectJson.substring(bngIndex, endIndex+1);
                    list.add(substring);
                    index++;
                }

                for (int i=0;i<list.size();i++){
                    String str = list.get(i);
                    boolean is = str.contains(bySchool);
                    if (is){
                        list.set(i,updateJson);
                        break;
                    }
                }

                for (int i=0;i<list.size();i++){
                    if (rst.equals("")) {
                        rst = "[" + list.get(i);
                    }else {
                        rst = rst +","+ list.get(i);
                    }
                }
                rst = rst + "]";
        }
        return rst;
    }


//    public static void main(String[] args) {
//        String updateJson = "[{\"rxTime\":\"2012年09月\",\"byTime\":\"2015年06月\",\"bySchool\":\"涉外经济学院\"}]";
//        String selectJson ="[{\"rxTime\":\"2012年09月\",\"byTime\":\"2015年06月\",\"bySchool\":\"长沙市第一中学\"},{\"rxTime\":\"2015年09月\",\"byTime\":\"2019年06月\",\"bySchool\":\"湖南大学\"}]";
//        String bySchool = "湖南大学";
//        String s = setUpdateJson(selectJson, bySchool, updateJson);
//        System.out.println(s);
//    }


//    public static void main(String[] args) throws UnsupportedEncodingException {
//        String a = "%E9%93%81%E9%81%93%E5%AD%A6%E9%99%A2";
//        String encodeStr = URLEncoder.encode("中国", "utf-8");
//        System.out.println("处理后:" + encodeStr);
//
//        //处理后:%E4%B8%AD%E5%9B%BD
//
//
//        String decodeStr = URLDecoder.decode(a, "utf-8");
//        System.out.println("解码:" + decodeStr);
//
//    }

}
